package com.huitone.gddw.controller.business;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huitone.gddw.controller.common.CommonController;
import com.huitone.gddw.dao.entity.SmModule;
import com.huitone.gddw.dao.entity.SmLog;
import com.huitone.gddw.model.support.Message;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.ISmModuleService;
import com.huitone.gddw.service.dto.SmModuleDTO;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 短信模板控制器
 * @author Weiliyu
 *
 */
@Controller
@RequestMapping(value="smModule")
public class SmModuleController extends CommonController {
	
	private final static Logger LOGGER = Logger.getLogger(SmModuleController.class);
	
	@Autowired
	private ISmModuleService smModuleService;
	
	/**
	 * 查询
	 * @param page
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="query")
	public QueryPage<SmModuleDTO> query(QueryPage<SmModule> page, HttpServletRequest request){
		super.logType = SmLog.LOGTYPE_SELECT;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]查询短信模板信息";
		Map<String, Object> params = new HashMap<String, Object>();
		String svrNode = request.getParameter("svrNode");
		String serviceCode = request.getParameter("serviceCode");
		String smTemplet = request.getParameter("smTemplet");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		params.put("svrNode", svrNode);
		params.put("serviceCode", serviceCode);
		params.put("smTemplet", smTemplet);
		params.put("startDate", startDate);
		params.put("endDate", endDate);
		page.setParams(params);
		QueryPage<SmModuleDTO> result = null;
		try {
			result = smModuleService.selectPage(page);
		} catch (Exception e) {
			LOGGER.error("查询短信模板信息出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return result;
	}

	/**
	 * 保存
	 * @param entity
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="save")
	public Message save(SmModule entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]添加短信模板信息";
		boolean isSuccess = true;
		String msg;
		try {
			Message message = this.optimize(entity.getSmTemplet());
			if (!message.isSuccess) {
				return message;
			}
			smModuleService.save(entity);
			msg = "保存成功！";
		} catch (Exception e) {
			LOGGER.error("保存短信模板信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "保存失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 删除
	 * @param smTempletId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="delete")
	public Message delete(String smTempletId) {
		super.logType = SmLog.LOGTYPE_DELETE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]删除短信模板信息";
		boolean isSuccess = true;
		String msg;
		try {
			smModuleService.delete(smTempletId);
			msg = "删除成功！";
		} catch (Exception e) {
			LOGGER.error("删除短信模板信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "删除失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 获取要修改的数据
	 * @param smTempletId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="toUpdate")
	public SmModule toUpdate(String smTempletId) {
		try {
			SmModule smModule = smModuleService.selectByPrimaryKey(smTempletId);
			return smModule;
		} catch (Exception e) {
			LOGGER.error("跳转修改页面过程中出现异常：" + e.getMessage(), e);
			return new SmModule();
		}
	}
	
	/**
	 * 修改
	 * @param entity
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="update")
	public Message update(SmModule entity) {
		super.logType = SmLog.LOGTYPE_UPDATE;
		super.logContent = "[" + SysLoginUtil.getLoginUserId() + "]修改短信模板信息";
		boolean isSuccess = true;
		String msg;
		try {
			SmModule smModule = smModuleService.selectByPrimaryKey(entity.getSmTempletId());
			smModule.setSvrNode(entity.getSvrNode());
			smModule.setServiceCode(entity.getServiceCode());
			smModule.setUsernums(entity.getUsernums());
			smModule.setSmTemplet(entity.getSmTemplet());
			smModule.setSendTime(entity.getSendTime());
			smModule.setSendRate(entity.getSendRate());
			smModule.setSendRateUnit(entity.getSendRateUnit());
			smModule.setRemark(entity.getRemark());
			smModuleService.update(smModule);
			msg = "修改成功！";
		} catch (Exception e) {
			LOGGER.error("修改短信模板信息过程中出现异常：" + e.getMessage(), e);
			super.logResult = SmLog.RESULT_FAIL;
			isSuccess = false;
			msg = "修改失败！";
		}
		super.saveSmLog(super.logType, super.logContent, super.logResult);
		return new Message(isSuccess, msg);
	}
	
	/**
	 * 更改状态
	 * @param smTempletId
	 * @param status
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="changeStatus")
	public Message changeStatus(String smTempletId, String status){
		try {
			SmModule entity = smModuleService.selectByPrimaryKey(smTempletId);
			entity.setStatus(status);
			smModuleService.update(entity);
			return new Message(true, "操作成功！");
		} catch (Exception e) {
			LOGGER.error("更改短信模板态过程中出现异常："+e.getMessage(), e);
			return new Message(false, "操作失败！");
		}
	}
	
	/**
	 * 短信模板结构优化分析
	 * @param limitByte
	 * @param smTemplet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="optimize")
	public Message optimize(String smTemplet){
		try {
			String msg;
			byte[] buff = smTemplet.getBytes();
			int smLength = buff.length;
			int smCount = smLength/134;
			int overlength = smLength%134;
			float a = (float)overlength/2;
			int b = Math.round(a);
			//最后一条短信少于6个字(12个字节)
			if (b <= 6 && smCount > 0) {
				msg = "分析成功，拆分后最后一条短短信长度为"+b+"个字，建议优化！";
			}else {
				msg = "分析成功，无需优化！";
			}
			return new Message(true, msg);
		} catch (Exception e) {
			LOGGER.error("短信模板结构优化分析过程中出现异常："+e.getMessage(), e);
			return new Message(false, "优化分析失败！");
		}
	}
}
